<?php
/**
 * @author eagle
 * @version 2014-7-30 上午8:54:54
 */
class Task_Ebaymailcron extends Minion_Task
{
    /**
     * Generates a help list for all tasks
     *
     * @return null
     */
    protected $_options = array(
        'start' => NULL,
        'end' => NULL,
    );

    //php f:\wamp\www\newerp\index.php --task=delivery --start="2014-03-27 " --end="2014-03-27 23:59:28"

    protected function _execute(array $params)
    {
        date_default_timezone_set('UTC');
	#set_time_limit(180);

        echo '任务[ebaymail]执行开始日期：' . date('Y-m-d H:i:s') . "\n";

        //防止进程过多
        $process 	= system("ps aux|grep 'task=ebaymailcron'|wc -l", $retval);
	echo '进程ebaymailcron数:'.$process;
        if (intval($process) > 20) {
	    echo '进程数过多:'.$process."\n";
            exit;
        }


        $sql = "SELECT * FROM ebay_account
            WHERE ebay_token != ''
	    AND `lock`=0
	    ORDER BY message_updtime ASC";

        $ebay_account_list = DB::query(Database::SELECT, $sql)
            ->execute('ebaymail')
            ->as_array();

        //将数据打乱
	if(rand(1,10)==5){

	}else{
        	shuffle($ebay_account_list);
	}

        foreach ($ebay_account_list as $key => $_account) {
	    if($key>=5){
		break;
	    }
            //开始时间的处理
            $sql = "SELECT message_updtime FROM ebay_account WHERE id=" . $_account['id'];
            $message_updtime = DB::query(Database::SELECT, $sql)
                ->execute('ebaymail')
                ->current();
            if (isset($message_updtime['message_updtime']) && $message_updtime['message_updtime']) {
                $start = date('Y-m-d H:i:s', strtotime($message_updtime['message_updtime']) - 120);
            } else {
                $start = date('Y-m-d H:i:s', time() - 60 * 30);
            }
            $end = date('Y-m-d H:i:s');
	    echo 'Log,account:'.$_account['ebay_account'].',数据库时间:'. $message_updtime['message_updtime'].',start:'.$start.',end:'.$end."\n";

            $num 	= ebayapi::get_member_messages($start, $end, $_account['ebay_token'], $_account['ebay_account']);
	    echo '写入数据:'.$num."\n";
        }

	//echo 'errprs_ackmessage';
        /* 检查错误的message */
	/*
        $sql = "SELECT * FROM errors_ackmessage WHERE status=0 LIMIT 0,1000 ";
        $errors_ackmessage_list = DB::query(Database::SELECT, $sql)
            ->execute('ebaymail')
            ->as_array();
        foreach ($errors_ackmessage_list as $_list) {
            $sql = "SELECT ebay_token FROM ebay_account WHERE ebay_account = '" . $ebay_account . "'";
            $ebay_account_temp = DB::query(Database::SELECT, $sql)
                ->execute('ebaymail')
                ->current();
            ebayapi::get_member_messages($_list['starttime'], $_list['endtime'], $ebay_account_temp['ebay_token'], $_list['ebay_account'], $_list['id']);
        }
	*/
        echo '任务[ebaymail]执行结束日期：' . date('Y-m-d H:i:s') . "\n";

    }
}
